package com.reus.core;

import java.util.ArrayList;
import java.util.List;

/**
 * description: 将sql语句拆分为sql部分和参数部分,因为我们需要使用java对象对数据库预处理对象进行注入。具体看下面例子
 *
 * @author liuxq@isyscore.com
 * @version 1.0
 * @example select * from users where id = {user.id} and name = {user.name}
 * -> sql = select * from users where id = ? and name = ?
 * -> paramResult = {user.id,user.name}
 * copyright: Copyright (c) 2018-2021
 * company: iSysCore Tech. Co., Ltd.
 * @date 2021-10-19 19:09:09
 */
public class SqlSource {
    /**
     * sql语句，待输入字段替换成?
     */
    private String sql;
    /**
     * 待输入字段
     */
    private List<String> param;
    /**
     * select update insert delete
     */
    private Integer executeType;

    public SqlSource(String sql) {
        this.param = new ArrayList<>();
        this.sql = sqlInject(this.param, sql);
    }

    /**
     * sql注入，对要注入的属性，必须使用{} 包裹，并替换为？ 见例子
     */
    private String sqlInject(List<String> paramResult, String sql) {

        String labelPrefix = "{";

        String labelSuffix = "}";
        // 将语句的所有的{}全部都解析成？,并将{xxx}中的xxx提取出来。
        while (sql.indexOf(labelPrefix) > 0 && sql.indexOf(labelSuffix) > 0) {
            String sqlParamName = sql.substring(sql.indexOf(labelPrefix), sql.indexOf(labelSuffix) + 1);
            sql = sql.replace(sqlParamName, "?");
            paramResult.add(sqlParamName.replace("{", "").replace("}", ""));
        }
        return sql;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public List<String> getParam() {
        return param;
    }

    public void setParam(List<String> param) {
        this.param = param;
    }

    public Integer getExecuteType() {
        return executeType;
    }

    public void setExecuteType(Integer executeType) {
        this.executeType = executeType;
    }
}
